package com.mspbots.sync.wise.service;

import com.mspbots.sync.BaseGenericService;
import com.mspbots.sync.callback.WiseNoticeProperties;
import com.mspbots.sync.callback.params.CallbackParam;
import com.mspbots.sync.utils.WiseParamsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

/**
 * com.mspbots.sync.callback.WiseCallbackService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/10/9
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class CallbackService extends BaseGenericService {

    private final WiseNoticeProperties properties;

    public Mono<Object> getCallbacks(Integer tenant) {
        return this.onGetWiseProperties(tenant)
                .flatMap(properties -> cwWebClient.getRepository("/system/callbacks",
                        WiseParamsUtils.queryParamsBuild("1", null))
                        .subscriberContext(ctx -> ctx.put("properties", properties)));
    }

    public Mono<Object> putCallbacks(Integer tenant, Integer id, CallbackParam body) {
        if (StringUtils.isEmpty(body.getUrl())) {
            body.setUrl("https://" + this.properties.getHost() + "/wise/notice/" + tenant + "/callback");
        }
        return this.onGetWiseProperties(tenant)
                .flatMap(properties -> cwWebClient.putRepository("/system/callbacks/" + id, body)
                        .subscriberContext(ctx -> ctx.put("properties", properties)));
    }

    public Mono<Object> deleteCallbacks(Integer tenant, Integer id) {
        return this.onGetWiseProperties(tenant)
                .flatMap(properties -> cwWebClient.deleteRepository("/system/callbacks/{id}", String.valueOf(id))
                        .subscriberContext(ctx -> ctx.put("properties", properties)));
    }

    public Mono<Object> postCallbacks(Integer tenant, CallbackParam body) {
        if (StringUtils.isEmpty(body.getUrl())) {
            body.setUrl("https://" + this.properties.getHost() + "/wise/notice/" + tenant + "/callback?id=");
        }
        return this.onGetWiseProperties(tenant)
                .flatMap(properties -> cwWebClient.postRepository("/system/callbacks", body)
                        .subscriberContext(ctx -> ctx.put("properties", properties)));
    }
}
